package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.authenticator.Obfuscator;
import com.conversationboard.model.Bookmarks;
import com.conversationboard.model.User;

@WebServlet(name = "DeleteBookmarkControllerServlet", urlPatterns = "/DeleteBookmarkControllerServlet")
public class DeleteBookmarkControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 1626294362645494952L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			int boardId = Integer.parseInt(request.getParameter("boardid"));
			int threadId = Integer.parseInt(request.getParameter("threadid"));

			Principal principal = request.getUserPrincipal();

			if (principal == null) {
				return;
			}

			/* Check authenticity */

			User user = User.get(principal.getName());

			String key = request.getParameter("sid");

			if (key == null) {
				return;
			}

			String decrypted = Obfuscator.decrypt(key);

			if (!decrypted.equals(request.getSession().getId())) {
				return;
			}

			Bookmarks.delete(null, user.getUserId(), boardId, threadId);
			user.getBookmarks().remove(Bookmarks.getKey(boardId, threadId));

		} catch (NumberFormatException e) {
		} catch (SQLException e) {
			throw new ServletException(e);
		}
	}

}
